package bookez.model.service.impl;

import java.util.List;

import bookez.model.businessobject.BusType;
import bookez.model.dao.BusTypeDao;
import bookez.model.exception.BusinessLogicLayerException;
import bookez.model.exception.DataAccessLayerException;
import bookez.model.service.BusTypeService;
import bookez.model.service.GenericService;

public class CachedBusTypeServiceImpl extends GenericService<BusTypeDao> implements BusTypeService {

	public CachedBusTypeServiceImpl() throws BusinessLogicLayerException {		
	}//end default constructor
		
	@Override
	public List<BusType> getAllBusType() throws BusinessLogicLayerException {
		// TODO Auto-generated method stub
		makeCachedReady();
		
		return getCached();
	}//end method getAllBusType

	@Override
	public BusType getBusTypeById(Long id) throws BusinessLogicLayerException {
		// TODO Auto-generated method stub
		makeCachedReady();
		
		for( BusType type : getCached() ) {
			if( type.getId().equals( id ) ) {
				return type;
			}
		}//end for
		
		// No matches
		return null;
	}//end method getBusTypeById

	@Override
	public BusType getBusTypeByName(String name)
			throws BusinessLogicLayerException {
		// TODO Auto-generated method stub
		makeCachedReady();
		
		for( BusType type : getCached() ) {
			if( type.getName().equalsIgnoreCase( name ) ) {
				return type;
			}
		}
		
		// No matches
		return null;
	}//end method getBusTypeByName

	@Override
	public boolean saveBusType(BusType type) throws BusinessLogicLayerException {
		// TODO Auto-generated method stub
		makeCachedReady();
		boolean isSaved = false;
		
		
		
		
		return isSaved;
	}//end method saveBusType

	@Override
	public boolean createBusType(BusType type)
			throws BusinessLogicLayerException {
		// TODO Auto-generated method stub
		return false;
	}//end method createBusType
	
	private void makeCachedReady() throws BusinessLogicLayerException {
		if( getCached() == null ) {
			buildCache();
		}
	}//end method makeCachedReady
	
	private void buildCache() throws BusinessLogicLayerException {
		List<BusType> result = null;
		
		try {
			result = getDao().findAll();
		}//end try
		
		catch( DataAccessLayerException dalEx ) {
			throw new BusinessLogicLayerException( dalEx );
		}//end catch
		
		setCached( result );
	}//end method buildCached
	
	@SuppressWarnings("unused")
	private boolean isCached( BusType type ) {
		if( getCached() == null ) {
			return false;
		}
		
		for( BusType cachedType : getCached() ) {
			if( cachedType.equals( type ) ) {
				return true;
			}
		}
		return false;
	}//end method isCached
	
	private List<BusType> getCached() { return this.cached; }
	private void setCached( List<BusType> value ) { this.cached = value; }

	private List<BusType> cached;
}//end class CachedBusTypeServiceImpl
